﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using KeepAccounts.Common.Aliyun.SMS;
using KeepAccounts.Common.Config;
using KeepAccounts.Common.Utilities;
using KeepAccounts.Models.Enums.Sms;
using KeepAccounts.Models.Models.Sms;
using KeepAccounts.Repository.Sms;
using Newtonsoft.Json;
using KeepAccounts.Models;

namespace KeepAccounts.Service.Domain.Sms
{
    public class SmsService : ISmsService
    {
        private readonly ISmsRepository _smsRepository;

        public SmsService(ISmsRepository smsRepository)
        {
            _smsRepository = smsRepository;
        }

        #region SendPhoneCode
        /// <summary>
        /// 发送手机验证码
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<object> SendPhoneCode(SendPhoneCodeModel model)
        {
            if (!ValidStringHelper.ValidPhoneNumber(model.PhoneNumber))
            {
                throw new ApiException("手机号格式错误");
            }
            var code = StringExtend.RandomCode(true, 6);
            var templateModel = new SmsPhoneCodeModel() { code = code, product = "登录验证码" };
            SmsEntity entity = new SmsEntity()
            {
                PhoneNumbers = model.PhoneNumber,
                Type = SmsTypeEnum.验证码.GetHashCode(),
                TemplateCode = WebConfig.SmsSendPhoneCode,
                TemplateParameter = JsonConvert.SerializeObject(templateModel)
            };
            await _smsRepository.Add(entity);
            await Send(entity);
            return $"验证码发送成功!{code}";
        }
        #endregion

        #region Ulit

        #region 发送短信
        private async Task<bool> Send(SmsEntity entity)
        {
            SmsSendModel model = new SmsSendModel()
            {
                PhoneNumbers = entity.PhoneNumbers.Split(",").ToList(),
                OutId = entity.ID.ToString(),
                SignName = WebConfig.SmsSignName,
                TemplateCode = WebConfig.SmsSendPhoneCode,
                TemplateParam = entity.TemplateParameter,
            };
            var result = SmsHelpter.SendSms(model);
            entity.ResponseParameter = result.Message;
            entity.IsSuccess = "ok".Equals(result.Code.ToLower());
            entity.BizId = result.BizId ?? string.Empty;
            entity.UpdateTime = DateTime.Now;
            await _smsRepository.Update(entity);
            return entity.IsSuccess;
        }
        #endregion

        #endregion


    }
}
